package com.jty.lib_base.utils

import android.app.ActivityManager
import android.content.Context
import android.graphics.*
import com.blankj.utilcode.util.PathUtils
import com.orhanobut.logger.Logger
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*


/**
 * author: zhouyh
 * created on: 2022/3/9 8:54 上午
 * description:
 */
object ComUtils {

    fun byte2FitMemorySize(byteNum: Long): String? {
        return if (byteNum < 0) {
            "shouldn't be less than zero!"
        } else if (byteNum < 1024) {
            String.format(Locale.getDefault(), "%.0fB", byteNum.toDouble())
        } else if (byteNum < 1048576) {
            String.format(Locale.getDefault(), "%.0fKB", byteNum.toDouble() / 1024)
        } else if (byteNum < 1073741824) {
            String.format(Locale.getDefault(), "%.0fMB", byteNum.toDouble() / 1048576)
        } else {
            String.format(Locale.getDefault(), "%.0fGB", byteNum.toDouble() / 1073741824)
        }
    }

    fun getHashmapByStr(
        keyArray: Array<String>, valueArray: Array<Any>,
    ):HashMap<String, Any>? {
        val map = HashMap<String,Any>()
        if (keyArray.size != valueArray.size) {
            ToastHelper.showErrorToast("key value长度不对应")
        } else {
            for (i in keyArray.indices){
                map[keyArray[i]] = valueArray[i]
            }
        }
        return map
    }

    /*
     * 判断服务是否启动,context上下文对象 ，className服务的name
     */
    fun isServiceRunning(mContext: Context, className: String): Boolean {
        var isRunning = false
        val activityManager = mContext
            .getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val serviceList = activityManager
            .getRunningServices(30)
        if (serviceList.size <= 0) {
            return false
        }
        for (i in serviceList.indices) {
            if (serviceList[i].service.className == className == true) {
                isRunning = true
                break
            }
        }
        return isRunning
    }

    /**
     * 判断是否过期
     */
    fun isResearchExpired(str : String):Boolean{
        val currentTime = System.currentTimeMillis()
        val lastTime = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(str).time
        return currentTime > lastTime
    }

    //剩余时间
    fun leftTime(time: Int):String{
        val mFormatBuilder = StringBuilder()
        val minutes = time % 60
        val hours = time / 60 % 24
        val days = time / 60 / 24

        mFormatBuilder.setLength(0)
        val mFormatter = Formatter(mFormatBuilder, Locale.getDefault())
        return if (days > 0) {
            mFormatter.format(" %d 天 %d 时 %02d 分", days, hours, minutes).toString()
        } else if (hours > 0){
            mFormatter.format(" %d 时 %02d 分", hours, minutes).toString()
        }else{
            mFormatter.format(" %02d 分", minutes).toString()
        }
    }

    fun combineBitmap(
        background: Bitmap,
        foreground: Bitmap,
        rect_width: Int,
        rect_height: Int,
    ): Bitmap? {
        var background = background
        var foreground = foreground
        if (background == null || foreground == null) {
            return null
        }
        var bgWidth = background.width
        var bgHeight = background.height
        var fgWidth = foreground.width
        var fgHeight = foreground.height
        var width = bgWidth
        var height = bgHeight
        if (bgWidth < fgWidth) {
            width = fgWidth
        }
        if (bgHeight < fgHeight) {
            height = fgHeight
        }
        var fScale = 1f
        if (width > rect_width) {
            fScale = if (rect_width <= 0) 1f else rect_width * 1.0f / width
            val matrix = Matrix()
            matrix.postScale(fScale, fScale) //长和宽放大缩小的比例
            background = Bitmap.createBitmap(
                background,
                0,
                0,
                background.width,
                background.height,
                matrix,
                true
            )
            foreground = Bitmap.createBitmap(
                foreground,
                0,
                0,
                foreground.width,
                foreground.height,
                matrix,
                true
            )
            bgWidth = background.width
            bgHeight = background.height
            fgWidth = foreground.width
            fgHeight = foreground.height
            width = bgWidth
            height = bgHeight
            if (bgWidth < fgWidth) {
                width = fgWidth
            }
            if (bgHeight < fgHeight) {
                height = fgHeight
            }
        }
        if (width < rect_width) {
            width = rect_width
        }
        if (height < rect_height) {
            height = rect_height
        }
        val newmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(newmap)
        val rect_paint = Paint()
        rect_paint.color = Color.parseColor("#ffffff")
        rect_paint.style = Paint.Style.FILL
        canvas.drawRect(Rect(0, 0, width, height), rect_paint)
        canvas.drawBitmap(background!!, 0f, 0f, null)
        canvas.drawBitmap(foreground!!, 0f, 0f, null)
        canvas.save()
        canvas.restore()
        return newmap
    }

    fun combineBitmap(foreground: Bitmap, rect_width: Int, rect_height: Int): Bitmap? {
        var foreground = foreground ?: return null
        var fgWidth = foreground.width
        var fgHeight = foreground.height
        var width = fgWidth
        var height = fgHeight
        var fScale = 1f
        if (width > rect_width) {
            fScale = if (rect_width <= 0) 1f else rect_width * 1.0f / width
            val matrix = Matrix()
            matrix.postScale(fScale, fScale) //长和宽放大缩小的比例
            Logger.e("宽高缩放：w = $fgWidth, h = $fgHeight, fs = $fScale")
            foreground = Bitmap.createBitmap(
                foreground,
                0,
                0,
                foreground.width,
                foreground.height,
                matrix,
                true
            )
            fgWidth = foreground.width
            fgHeight = foreground.height
            width = fgWidth
            height = fgHeight
        }
        if (width < rect_width) {
            width = rect_width
        }
        if (height < rect_height) {
            height = rect_height
        }
        val newmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(newmap)
        val rect_paint = Paint()
        rect_paint.color = Color.parseColor("#ffffff")
        rect_paint.style = Paint.Style.FILL
        canvas.drawRect(Rect(0, 0, width, height), rect_paint)
        canvas.drawBitmap(foreground, 0f, 0f, null)
        canvas.save()
        canvas.restore()
        return newmap
    }


    /**
     * 合并两张bitmap为一张
     *
     * @param background
     * @param foreground
     * @return Bitmap
     */
    fun combineBitmap(background: Bitmap?, foreground: Bitmap?): Bitmap? {
        if (background == null || foreground == null) {
            return null
        }
        val bgWidth = background.width
        val bgHeight = background.height
        val fgWidth = foreground.width
        val fgHeight = foreground.height
        var width = bgWidth
        var height = bgHeight
        if (bgWidth < fgWidth) {
            width = fgWidth
        }
        if (bgHeight < fgHeight) {
            height = fgHeight
        }
        val newmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(newmap)
        canvas.drawBitmap(background, 0f, 0f, null)
        canvas.drawBitmap(foreground, 0f, 0f, null)
        canvas.save()
        canvas.restore()
        return newmap
    }

    @JvmStatic
    fun saveBitmap(dir: String?, b: Bitmap): String? {
        val dir = PathUtils.getExternalAppCachePath() + "/${dir}"
        val dirFile = File(dir)
        if (!dirFile.exists()) {
            dirFile.mkdirs()
        }
        val dataTake = System.currentTimeMillis()
        val jpegName = dir + File.separator + "picture_" + dataTake + ".jpg"
        val file = File(jpegName)
        if (!file.exists()){
            file.createNewFile()
        }
        return try {
            val fout = FileOutputStream(file)
            val bos = BufferedOutputStream(fout)
            b.compress(Bitmap.CompressFormat.JPEG, 100, bos)
            bos.flush()
            bos.close()
            jpegName
        } catch (e: IOException) {
            e.printStackTrace()
            ""
        }
    }
}